/**
 * 
 */
package com.ws.framework.service.impl;

import java.util.Iterator;
import java.util.List;

import org.apache.shiro.crypto.hash.DefaultHashService;
import org.apache.shiro.crypto.hash.HashRequest;
import org.apache.shiro.util.ByteSource;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException.NodeExistsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import com.google.common.base.Splitter;
import com.ws.framework.dao.AppDao;
import com.ws.framework.dao.UserDao;
import com.ws.framework.model.App;
import com.ws.framework.model.Page;
import com.ws.framework.service.AppService;
import com.ws.framework.util.ValidationUtil;
import com.ws.framework.zk.CuratorClient;

/**
 * <p>
 * </p>
 *
 * @author WSH
 */
@Service
public class AppServiceImpl implements AppService {

	@Autowired
	AppDao appDao;
	@Autowired
	UserDao userDao;
	@Autowired
	CuratorClient client;
	
	@Override
	public Page<App> select4Page(Page<App> page) {
		return appDao.select4Paget(page);
	}

	/**
	 * 注册应用信息，应用在使用之前，必须在dynamic控制台注册其信息，并领取一个私钥用于和dynamic通讯。
	 */
	@Override
	public boolean insert(App app) {
		try {
			for (Iterator<String> it = Splitter.on(";").split(app.getCodeManagers()).iterator(); it.hasNext();) {
				DefaultHashService hashService = new DefaultHashService();
				HashRequest request = new HashRequest.Builder().setSource(ByteSource.Util.bytes("123456")).build();
				String hex = hashService.computeHash(request).toHex();
				userDao.inserUser(it.next(), hex);
			}
			app.setPriKey(ValidationUtil.getHmacKey());
			app.setPubKey("register");
			boolean result = appDao.insert(app) > 0;
			String path = getZkPath(app.getAppCode());
			client.getClient().create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path);
			return result;
		} catch (NodeExistsException e1) {
			//ignore
			return true;
		} catch (DuplicateKeyException e2) {
			throw e2;
		}  catch (Exception e) {
			throw new RuntimeException("注册应用信息出现异常", e);
		}
	}

	@Override
	public List<App> selectAppByManager(String manager) {
		return appDao.selectAppByManager(manager);
	}

	@Override
	public App selectAppById(long id) {
		return appDao.selectAppById(id);
	}

	@Override
	public App selectAppByCode(String code) {
		return appDao.selectAppByCode(code);
	}

	private String getZkPath(String code) {
		return "/app/" + code + "/dynamic";
	}
}
